package com.authine.cloudpivot.engine.service.bizrule.handler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression.Op;
import com.authine.cloudpivot.engine.component.query.api.Order;
import com.authine.cloudpivot.engine.component.query.api.Pageable;
import com.authine.cloudpivot.engine.component.query.api.Sortable;
import com.authine.cloudpivot.engine.component.query.api.helper.OrderImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.component.query.api.helper.SortableImpl;
import com.authine.cloudpivot.engine.domain.runtime.BizObject;
import com.authine.cloudpivot.engine.enums.status.DataRowStatus;
import com.authine.cloudpivot.engine.enums.type.DefaultPropertyType;
import com.authine.cloudpivot.engine.open.domain.bizmodel.BizObjectQuery;
import com.authine.cloudpivot.engine.open.service.OpenEngine;
import com.authine.cloudpivot.engine.service.bizrule.handler.context.Request;
import com.google.common.collect.Lists;

public class 周报填充 extends BaseHandler {
    private static final Logger LOG = LoggerFactory.getLogger("在线编码-优化事项-优化事项周报-填充周报内容");
    private static final String YHSX_KEY = "OptimizeItemNew";
    private static final String ZRR_KEY = "ProjectResponsiblePerson";
    private static final String CHILE_SCHEMA_CODE = "NextWeekPlanForm";
    private String glsxid = null;
    private String zrrid = null;

    @SuppressWarnings("unchecked")
    @Override
    public Object handle(Request request) {
        /* 获取开放引擎 */
        OpenEngine engine = this.getOpenEngine(request);
        /* 获取触发数据 */
        BizObject bizObject = request.getData().getBizObject();
        Map<String, Object> data = bizObject.getData();
        /* 获取优化事项ID 关联单选 */
        Object glsx = data.get(YHSX_KEY);
        if (glsx != null && glsx instanceof Map) {
            Object temp = ((Map<String, Object>) glsx).get("id");
            glsxid = temp == null ? null : temp.toString();
        }
        /* 获取责任人ID 人员单选 */
        Object zrr = data.get(ZRR_KEY);
        if (zrr != null && zrr instanceof List) {
            /* 获取第一个元素 */
            Object first = ((List<?>) zrr).get(0);
            if (first != null && first instanceof SelectionValue) {
                zrrid = ((SelectionValue) first).getId();
            }
        }
        if (glsxid != null && zrrid != null) {
            /* 获取上一个数据 查询逻辑 根据优化事项和责任人查询并排除自己 查询最近两条按创建时间降序排序 */
            List<BizObject> targets = engine.listBizObjects(new BizObjectQuery() {
                private static final long serialVersionUID = 1L;

                @Override
                public String getSchemaCode() {
                    return bizObject.getSchemaCode();
                }

                @Override
                public FilterExpression getFilterExpression() {
                    return Q.and(Q.it("id", Op.NotEq, bizObject.getId()), Q.it(YHSX_KEY, Op.Eq, glsxid), Q.it(ZRR_KEY, Op.Eq, zrrid), Q
                            .it(DefaultPropertyType.CREATED_TIME.getCode(), Op.Lt, data.get(DefaultPropertyType.CREATED_TIME.getCode())));
                }

                @Override
                public Sortable getSortable() {
                    return new SortableImpl(Lists.newArrayList(new OrderImpl(DefaultPropertyType.CREATED_TIME.getCode(), Order.Dir.DESC)));
                }

                @Override
                public Pageable getPageable() {
                    return new PageableImpl(0, 2);
                }
            });
            /* 判断数据是否为空 */
            if (targets != null && !targets.isEmpty()) {
                BizObject target = targets.get(0);
                BizObject previous = engine.getBizObject(target.getSchemaCode(), target.getId(), Arrays.asList(CHILE_SCHEMA_CODE));
                List<Map<String, Object>> datas = (List<Map<String, Object>>) previous.getData().get(CHILE_SCHEMA_CODE);
                List<Map<String, Object>> news = new ArrayList<>();
                datas.stream().forEach(m -> {
                    Map<String, Object> temp = new HashMap<>();
                    temp.put(BizObject.DATAROWSTATUS, DataRowStatus.Added);
                    temp.put("describe1", m.get("describe"));
                    temp.put("planFinishDate1", m.get("planFinishDate"));
                    temp.put("pushManager2", m.get("pushManager1"));
                    news.add(temp);
                });
                bizObject.getData().put("NextWeekPlanForm1", news);
                engine.updateBizObject(bizObject, true);
                LOG.info("===>>初始化子表成功 匹配目标数据时间：{} 数据：{}", previous.getData().get(DefaultPropertyType.CREATED_TIME.getCode()), news);
            } else {
                LOG.info("===>>未找到合适数据");
            }
        } else {
            LOG.info("===>>优化事项和责任人为空 不执行赋值操作,触发数据ID:{},数据：{}", bizObject.getId(), bizObject.getData());
        }

        return bizObject;
    }
}
